package com.heima.comment.Service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.user.UserFeignClient;
import com.heima.comment.Service.CommentService;
import com.heima.comment.dtos.CommentLikeDto;
import com.heima.comment.dtos.CommentListDto;
import com.heima.comment.dtos.CommentSaveDto;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.vo.ApCommentVo;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeignClient client;
    @Autowired
    private GreenTextScan textScan;

    /**
     * 保存评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //1.检查参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getContent() != null && dto.getContent().length() > 150) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "评论内容不能超过140字");
        }
        //2.判断是否登录
        ApUser user = ApThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.5 判断如果是游客身份则不允许发表评论
        if (user.getId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "请登录之后再来评论！！");
        }
        //3.查询用户信息------先从redis中查询，如果不存在再从用户微服务中去查询
        String userStr = redisTemplate.opsForValue().get("LOGIN_USER_" + user.getId());
        if (StringUtils.isBlank(userStr)) {
            //表示redis中没有用户的数据,就用 feign远程调用user服务
            ResponseResult<ApUser> result = client.findUserById(user.getId().longValue());
            if (result.getCode() == 200 && result.getData() != null) {
                user = result.getData();
                //存入到redis中,并设置两个小时过期时间
                redisTemplate.opsForValue().set("LOGIN_USER_" + user.getId(), JSON.toJSONString(user), 2, TimeUnit.HOURS);
            }
        } else {
            //表示redis中有用户的数据,直接取出
            user = JSON.parseObject(userStr, ApUser.class);
        }
        //4.对评论信息进行安全过滤
        Boolean textFilter = scanTextFilter(dto.getContent());
        if (!textFilter) {
            //表示违规
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMENT_BLOCK);
        }
        //5.保存数据到mongo中
        ApComment apComment = new ApComment();
        apComment.setId(ObjectId.get().toHexString());
        apComment.setUserId(user.getId());
        apComment.setNickName(user.getName());
        apComment.setImage(user.getImage());
        apComment.setTargetId(dto.getArticleId()+"");
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        mongoTemplate.insert(apComment);
        return ResponseResult.okResult("评论成功");
    }

    /**
     * 对评论信息进行安全审核
     *
     * @param content
     */
    private Boolean scanTextFilter(String content) {
        Boolean flag = true;
        try {
            Map map = textScan.greeTextScan(content);
            if (map != null && !map.get("suggestion").equals("pass")) {//表示违规
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 评论点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //1.检查参数
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.判断是否登录
        ApUser user = ApThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.5 判断如果是游客身份则不允许发表评论
        if (user.getId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "请登录之后再来点赞！！");
        }
        //判断当前评论信息是否存在，如果不存在，直接返回
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询redis,是否有点赞过
        //定义key
        String comment_likes_key = "COMMENT_LIKE_" + user.getId();
        //表示根据当前key下的所有的value中是否包含某一个，如果包含返回true,否则false
        Boolean member = redisTemplate.opsForSet().isMember(comment_likes_key, dto.getCommentId());
        //4 如果点赞过，并且现在正在执行的是点赞操作，直接返回
        if (member && dto.getOperation() == 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //5  如果点赞过，并且正在执行的是取消点赞，删除redis,删除mongo中点赞集合，修改mongo中的评论集合，点赞数-1
        if (member && dto.getOperation() == 1) {
            redisTemplate.opsForSet().remove(comment_likes_key, dto.getCommentId());
            mongoTemplate.remove(Query.query(Criteria.where("userId").is(user.getId()).and("targetId").is(dto.getCommentId())), ApCommentLike.class);
            //修改mongo中的评论集合，点赞数-1
            Query query = Query.query(Criteria.where("id").is(apComment.getId()).and("likes").gt(0));
            UpdateDefinition update = new Update().inc("likes", -1);
            mongoTemplate.updateFirst(query, update, ApComment.class);
        }
        //6 如果没有点赞过，并且正在执行的是点赞操作，新增redis,新增mongo中的点赞集合，修改mongo中的评论集合，点赞数+1
        if (!member && dto.getOperation() == 0) {
            redisTemplate.opsForSet().add(comment_likes_key, dto.getCommentId());
            //新增mongo中的点赞集合
            ApCommentLike commentLike = new ApCommentLike();
            commentLike.setId(ObjectId.get().toHexString());
            commentLike.setUserId(user.getId());
            commentLike.setTargetId(dto.getCommentId());
            commentLike.setCreatedTime(new Date());
            mongoTemplate.insert(commentLike);
            //修改mongo中的评论集合，点赞数+1
            Query query = Query.query(Criteria.where("id").is(apComment.getId()));
            UpdateDefinition update = new Update().inc("likes", 1);
            mongoTemplate.updateFirst(query, update, ApComment.class);
        }
        //以上情况都不是就返回数据
        apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        Map map = new HashMap();
        map.put("likes", apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    /**
     * 加载文章评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentListDto dto) {
        //1.检查参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        //最长显示50条
        //Math.min(x,y),取x,y中最小的一个赋值给Size
        dto.setSize(Math.min(dto.getSize(), 50));
        //2根据文章id去查询 mongo的评论表，并进行分页和排序展示
        Query query = Query.query(Criteria.where("targetId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime")) //根据创建时间排序
                .limit(dto.getSize()); //分页
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
        if (commentList == null && commentList.size()<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.如果此刻是游客登录的话，则直接返回评论列表
        ApUser user=ApThreadLocalUtil.getUser();
        if (user.getId()==0){
            return ResponseResult.okResult(commentList);
        }
        //4.否则就是用户登录，加载数据的时候，要判断当前用户点赞了拿些评论，并给予标识
        //4.1 查询redis中是否有点赞数据
        String key="COMMENT_LIKE_" + user.getId();
        //根据key查询出所有的值
        Set<String> members = redisTemplate.opsForSet().members(key);
        //4.2 如果没有查询到数据,则直接返回评论列表
        if (members==null){
            return ResponseResult.okResult(commentList);
        }
        //4.3 否则，就是存在点赞数据，则添加标记
        List<ApCommentVo> collect = commentList.stream().map(comment -> {
            ApCommentVo vo = new ApCommentVo();
            BeanUtils.copyProperties(comment, vo);
            if (members.contains(comment.getId())) {
                vo.setOperation((short) 0);
            }
            return vo;
        }).collect(Collectors.toList());
        //5.返回数据
        return ResponseResult.okResult(collect);
    }
}
